import { DataSource } from 'typeorm';
// 按照数据库表结构导入各个seed
import { PermissionSeed } from './entities/permission.seed';
import { RoleSeed } from './entities/role.seed';
import { RolePermissionSeed } from './entities/role-permission.seed';
import { UserSeed } from './entities/user.seed';
import { UserRoleSeed } from './entities/user-role.seed';
import { WorkspaceSeed } from './entities/workspace.seed';
import { WorkspaceMemberSeed } from './entities/workspace-member.seed';
import { ProjectSeed } from './entities/project.seed';
import { ProjectMemberSeed } from './entities/project-member.seed';
import { TagSeed } from './entities/tag.seed';
import { TaskSeed } from './entities/task.seed';
import { TaskTagSeed } from './entities/task-tag.seed';
import { TaskCommentSeed } from './entities/task-comment.seed';
import { TaskCommentReplySeed } from './entities/task-comment-reply.seed';
import { NotificationSeed } from './entities/notification.seed';
import { FileSeed } from './entities/file.seed';

// 新增：清空数据的功能
async function clearData(dataSource: DataSource) {
  console.log('开始清空数据...');
  
  try {
    // 删除表数据时需要考虑外键关系，从子表开始删除
    
    // 0. 删除files表
    try {
      await dataSource.query('DELETE FROM files');
      console.log('已清空files表');
    } catch (error) {
      console.log('清空files表时出错，可能表不存在');
    }
    
    // 1. 删除notifications表
    try {
      await dataSource.query('DELETE FROM notifications');
      console.log('已清空notifications表');
    } catch (error) {
      console.log('清空notifications表时出错，可能表不存在');
    }
    
    // 2. 删除task_comment_replies表
    try {
      await dataSource.query('DELETE FROM task_comment_replies');
      console.log('已清空task_comment_replies表');
    } catch (error) {
      console.log('清空task_comment_replies表时出错，可能表不存在');
    }
    
    // 3. 删除task_tags关联表
    await dataSource.query('DELETE FROM task_tags');
    console.log('已清空task_tags表');
    
    // 3. 删除task_comments表
    try {
      await dataSource.query('DELETE FROM task_comments');
      console.log('已清空task_comments表');
    } catch (error) {
      console.log('清空task_comments表时出错，可能表不存在');
    }
    
    // 4. 删除tasks表
    await dataSource.query('DELETE FROM tasks');
    console.log('已清空tasks表');
    
    // 5. 删除tags表
    await dataSource.query('DELETE FROM tags');
    console.log('已清空tags表');
    
    // 6. 删除project_members表
    await dataSource.query('DELETE FROM project_members');
    console.log('已清空project_members表');
    
    // 7. 删除projects表
    await dataSource.query('DELETE FROM projects');
    console.log('已清空projects表');
    
    // 8. 删除workspace_members表
    try {
      await dataSource.query('DELETE FROM workspace_members');
      console.log('已清空workspace_members表');
    } catch (error) {
      console.log('清空workspace_members表时出错，可能表不存在');
    }
    
    // 9. 删除workspaces表
    await dataSource.query('DELETE FROM workspaces');
    console.log('已清空workspaces表');
    
    // 10. 删除user_roles表（用户和角色的关联表）
    await dataSource.query('DELETE FROM user_roles');
    console.log('已清空user_roles表');
    
    // 11. 删除role_permissions表（角色和权限的关联表）
    await dataSource.query('DELETE FROM role_permissions');
    console.log('已清空role_permissions表');
    
    // 注意：以下三个表包含基础数据，通常不应清空
    // 如果需要完全重置系统，可以取消下面的注释
    
    // 删除permissions表（需慎重，包含系统基础权限）
    await dataSource.query('DELETE FROM permissions');
    console.log('已清空permissions表');
    
    // 删除roles表（需慎重，包含系统基础角色）
    await dataSource.query('DELETE FROM roles');
    console.log('已清空roles表');
    
    // 删除users表（需慎重，包含管理员账户）
    await dataSource.query('DELETE FROM users');
    console.log('已清空users表');
    
    console.log('数据清空完成！');
  } catch (error) {
    console.error('清空数据失败:', error);
    throw error;  // 让错误继续传播
  }
}

export async function runSeeds(dataSource: DataSource) {
  console.log('开始初始化数据...');
  
  // 先清空相关表的数据
  try {
    await clearData(dataSource);
  } catch (error) {
    console.error('清空数据过程中出错，但将继续尝试初始化:', error);
  }
  
  // 按照依赖关系顺序初始化数据
  try {
    // 1. 基础权限和角色
    const permissionSeed = new PermissionSeed(dataSource);
    await permissionSeed.run();
    
    const roleSeed = new RoleSeed(dataSource);
    await roleSeed.run();
    
    const rolePermissionSeed = new RolePermissionSeed(dataSource);
    await rolePermissionSeed.run();
    
    // 2. 用户及其角色
    const userSeed = new UserSeed(dataSource);
    await userSeed.run();
    
    const userRoleSeed = new UserRoleSeed(dataSource);
    await userRoleSeed.run();
    
    // 3. 工作区及成员
    const workspaceSeed = new WorkspaceSeed(dataSource);
    await workspaceSeed.run();
    
    const workspaceMemberSeed = new WorkspaceMemberSeed(dataSource);
    await workspaceMemberSeed.run();
    
    // 4. 项目及成员
    const projectSeed = new ProjectSeed(dataSource);
    await projectSeed.run();
    
    const projectMemberSeed = new ProjectMemberSeed(dataSource);
    await projectMemberSeed.run();
    
    // 5. 标签
    const tagSeed = new TagSeed(dataSource);
    await tagSeed.run();
    
    // 6. 任务及关联
    const taskSeed = new TaskSeed(dataSource);
    await taskSeed.run();
    
    const taskTagSeed = new TaskTagSeed(dataSource);
    await taskTagSeed.run();
    
    const taskCommentSeed = new TaskCommentSeed(dataSource);
    await taskCommentSeed.run();
    
    // 7. 任务评论回复
    const taskCommentReplySeed = new TaskCommentReplySeed(dataSource);
    await taskCommentReplySeed.run();
    
    // 8. 通知数据
    const notificationSeed = new NotificationSeed(dataSource);
    await notificationSeed.run();
    
    // 9. 文件数据
    const fileSeed = new FileSeed(dataSource);
    await fileSeed.run();
    
    console.log('数据初始化完成！');
  } catch (error) {
    console.error('数据初始化失败:', error);
    throw error;
  }
} 